package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Autowired
    WebSocketServer webSocketServer;

    /*
     * 下单
     * */
    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //查询当前用户收货地址信息（获取phone/address/username/consigee）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new OrderBusinessException("下单失败,请设置正确的收件地址");
        }

        //2.调用持久层，向order订单表中添加一条订单数据
        String orderNumber = UUID.randomUUID().toString();
        LocalDateTime orderTime = LocalDateTime.now();

        //2.1构建一个订单数据实体对象
        Orders orders = new Orders();
        orders.setNumber(orderNumber);//订单号
        orders.setStatus(Orders.PENDING_PAYMENT);//订单状态：待付款
        orders.setOrderTime(orderTime);//下单时间
        orders.setPayStatus(Orders.UN_PAID);//订单状态：未付款
        orders.setUserId(BaseContext.getCurrentId());//订单的属主


        //封装收件相关的信息
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(addressBook.getConsignee());
        orders.setConsignee(addressBook.getConsignee());

        //将tdo中的数据拷贝到orders实体对象
        BeanUtils.copyProperties(ordersSubmitDTO, orders);

        //2.2.2向order订单表中添加一条订单数据
        orderMapper.insert(orders); //注意：设置主键返回

        //检查用户的收货地址是否超出了范围
        //checkOutOfRange(addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());


        //3. 调用持久层，向order_detail订单明细表中添加多条数据
        //3.1 获取当前用户购物车中的商品个信息
        List<ShoppingCart> shoppingCartLisst = shoppingCartMapper.selectByCondition(ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .build());
        //3.2批量的添加到订单明细表中
        //构建订单明细集合
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartLisst) {
            //构建订单明细对象
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            //设置订单明细所属的订单
            orderDetail.setOrderId(orders.getId());
            //向集合中添加
            orderDetailList.add(orderDetail);
        }
        //3.3添加订单明细数据（批量添加）
        orderDetailMapper.insertBatch(orderDetailList);

        //4.清空购物车
        shoppingCartMapper.clean(BaseContext.getCurrentId());

        //5. 封装结果数据
        return OrderSubmitVO.builder()
                .orderNumber(orderNumber)//订单号
                .orderAmount(ordersSubmitDTO.getAmount())//下单总金额
                .orderTime(orderTime)//下单时间
                .id(orders.getId())//订单id
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        /*JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/
        JSONObject jsonObject = new JSONObject();

       /* if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }*/

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //1.来单提醒：服务器端主动推送来单提醒给商家端
        //2.封装响应的信息：json{type:"",orderId:"",content:""}
        Map map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", MessageConstant.NEW_ORDER_MSG);
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

    /**
     * @return 查询历史订单
     * @author 小陈
     * @DateTime:
     */
    @Override
    public PageResult pageQuery4User(int page, int pageSize, Integer status) {
        //开启分页
        PageHelper.startPage(page, pageSize);
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        //分页条件查询
        Page<Orders> page1 = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList<>();

        //查询订单明细，并封装入OrderVo进行响应
        if (page1 != null && page1.getTotal() > 0) {
            for (Orders orders : page1) {
                Long orderId = orders.getId();//订单id

                //查询明细
                List<OrderDetail> orderDetails = orderDetailMapper.geByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }
        }
        /*PageResult pageResult = new PageResult();
        pageResult.getTotal();
        pageResult.getRecords();*/
        //封装返回
        return new PageResult(page1.getTotal(), list);
    }

    /*
     * 查询订单详情
     * */
    @Override
    public OrderVO getById(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);

        //查询明细
        List<OrderDetail> orderDetails = orderDetailMapper.geByOrderId(orders.getId());

        //封装
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        //返回结果
        return orderVO;
    }

    /*
     * 取消订单
     *
     * */
    @Override
    public void Canceltheorder(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);

        //校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //校验订单状态是否不允许进行取消(已接单/派送中/已完成/已取消)
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        //判断订单状态是否是待接单状态，此状态下，需要执行退款逻辑

        //更新订单表数据
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason("用户取消");
        orders1.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders1);
    }

    /*
     * 再来一单
     *
     * */
    @Override
    public void Onemoreorder(Long id) {
        //查询订单明细，并封装入OrderVo进行响应
        Long userId = BaseContext.getCurrentId();

        //查询明细
        List<OrderDetail> orderDetails = orderDetailMapper.geByOrderId(id);

        //将订单详情对象转换为购物车对象

        orderDetails.forEach(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(BaseContext.getCurrentId());
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            //将购物车对象批量添加到数据库
            shoppingCartMapper.insert(shoppingCart);
        });
    }

    /*
     *
     * 订单搜索
     * */
    @Override
    public PageResult orderSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //开启分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        //遍历
        List<OrderVO> list = new ArrayList<>();

        //查询订单明细，并封装入OrderVo进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();//订单id

                //遍历订单集合，查询每一个订单的订单明细：select *from order_detail where order_id=？
                List<OrderDetail> orderDetails = orderDetailMapper.geByOrderId(orderId);

                //将订单Order集合装换成OrderVO集合
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);
                list.add(orderVO);
            }
        }
        /*PageResult pageResult = new PageResult();
        pageResult.getTotal();
        pageResult.getRecords();*/
        //封装PageResult,并返回
        return new PageResult(page.getTotal(), list);
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.geByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    /*
     * 各个状态的订单数量统计
     *
     * */
    @Override
    public OrderStatisticsVO statistics() {
        //分别查询出待接单，待派送，派送中的订单数量
        //select count(id) from orders where status =？
        Integer t = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer c = orderMapper.countStatus(Orders.CONFIRMED);
        Integer d = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        //将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(t);
        orderStatisticsVO.setConfirmed(c);
        orderStatisticsVO.setDeliveryInProgress(d);
        return orderStatisticsVO;
    }

    /*
     * 接单
     * */
    @Override
    public void Takeorders(OrdersConfirmDTO ordersConfirmDTO) {
        //补全属性
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        // 返回
        orderMapper.update(orders);

    }

    /*
     * 拒单
     * */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());

        // 订单只有存在且状态为2（待接单）才可以拒单
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //判断支付状态是否是已付款，如果是进行退款操作（此操作跳过）

        // 封装订单对象，设置订单状态，拒单原因、取消时间，修改订单数据
        //update orders set
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        orders1.setStatus(Orders.CANCELLED);
        orders1.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders1.setCancelTime(LocalDateTime.now());

        orderMapper.update(orders1);
    }

    /*
     * 取消订单
     *
     * */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        // 根据id查询订单
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());

        //判断支付状态是否是已付款，如果是进行退款操作（此操作跳过）


        // 封装订单对象，设置订单状态，拒单原因、取消时间，修改订单数据
        //update orders set
        Orders orders1 = new Orders();
        orders1.setId(ordersCancelDTO.getId());
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelReason(ordersCancelDTO.getCancelReason());
        orders1.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders1);
    }

    /*
     * 派送订单
     * */
    @Override
    public void delivery(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);

        // 订单只有存在且状态为3（已接单）
        if (orders == null || !orders.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 封装订单对象，设置订单状态为派送中
        //update orders set
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        // 更新订单状态,状态转为派送中
        orders1.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders1);

    }

    /*
     * 完成订单
     *
     * */
    @Override
    public void complete(Long id) {
        //根据id查询订单
        Orders orders = orderMapper.getById(id);
        // 订单只有存在且状态为4（派送中）
        if (orders == null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 封装订单对象，设置订单状态为派送中
        //update orders set
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());
        // 更新订单状态,状态转为派送中
        orders1.setStatus(Orders.COMPLETED);
        orders1.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders1);

    }

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap<>();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        // 获取店铺的经纬度信息
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址信息解析失败");
        }

        // 数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        // 店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);

        // 获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        // 数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        // 用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        // 路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        // 数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            // 配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /*
     * 客户催单
     *
     * */
    @Override
    public void reminder(Long id) {
        //1.查询订单是否存在
        Orders orders = orderMapper.getById(id);

        //2.如果订单催单，进行催单
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //2.1使用websocket
        //2.2客户进行催单的业务方法中进行催单
        //2.3如何封装催单的数据：json格式：type/orderId/content
        Map map = new HashMap();
        map.put("type", 2);//消息的类型：2催单
        map.put("orderId", id);
        map.put("content", "抓紧接单吧！人家付完钱都等了很长时间了！");

        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));//群发消息
    }

}



